package com.lkd.service.impl;
import com.google.common.collect.Lists;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.controller.BaseController;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskReportInfoVO;
import com.lkd.http.vo.TaskStatusCountVO;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.UserWorkVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }

    /**
     * 创建工单
     * @param taskViewModel
     * @return
     * @throws LogicException
     */
    @Transactional
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if(vm==null){
            throw new LogicException("该机器不存在");
        }

        //（1）创建工单，需要校验售货机的状态与工单类型是否相符，逻辑如下：
        // 如果是投放工单，状态为运营则抛出异常
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_DEPLOY && vm.getVmStatus() == VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("设备处于运行状态，无法创建投放工单");
        }
        // 如果是补货工单，状态不是运营状态则抛出异常
        // 如果是撤机工单，状态不是运营状态则抛出异常
        if ((taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY || taskViewModel.getProductType() == VMSystem.TASK_TYPE_REVOKE)
                && vm.getVmStatus() != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("设备未处于运营状态，无法创建补货或撤机工单");
        }
        //（2）我们在创建工单时应该校验这台设备是否有未完成的同类型工单，如果存在则不能创建。
        QueryWrapper<TaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode,taskViewModel.getInnerCode())
                .eq(TaskEntity::getProductTypeId,taskViewModel.getProductType())
                .le(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS);
        int count = this.count(queryWrapper);
        if (count > 1){
            throw new LogicException("该设备存在未完成的同类型工单，无法创建该工单");
        }
        //跨服务查询用户微服务，得到用户名
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if(user==null){
            throw new LogicException("该用户不存在");
        }

        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel,taskEntity);//复制属性
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型

        taskEntity.setAddr(vm.getNodeAddr());//地址
        taskEntity.setRegionId(  vm.getRegionId() );//区域
        taskEntity.setUserName(user.getUserName());//用户名
        this.save(taskEntity);
        //如果是补货工单，向 工单明细表插入记录
        if(taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            taskViewModel.getDetails().forEach(d->{
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties( d,detailsEntity );
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }
        updateTaskZSet(taskEntity,1);
        return true;
    }

    /**
     * 更新工单量列表
     * @param taskEntity
     * @param score
     */
    private void updateTaskZSet(TaskEntity taskEntity, int score) {
        String roleCode = "1003"; //运维人员
        if (taskEntity.getProductTypeId().intValue() == 2){ //如果是补货工单改为运营角色
            roleCode = "1002"; //运营人员
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + taskEntity.getRegionId() + "." + roleCode;
        redisTemplate.opsForZSet().incrementScore(key,taskEntity.getUserId(),score);
    }

    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key= "lkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001";
        }
        return date+  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }


    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId,VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    @Autowired
    private BaseController baseController;

    /**
     * 接收工单
     * @param id
     * @return
     */
    @Override
    public boolean accept(Long id) {
        TaskEntity task = this.getById(id);  //查询工单
        //（1）需要判断当前工单是否是待处理状态，如果不是则抛出异常。
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE){
            throw new LogicException("该工单状态不是待处理无法接收");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_PROGRESS );//修改工单状态为进行
        return this.updateById(task);
    }

    /**
     * 取消工单
     * @param id
     * @param cancelVM
     * @return
     */
    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);  //查询工单
        //（1）需要判断当前工单是否是未结束状态，如果是已完成或已取消则抛出异常。
        if (VMSystem.TASK_STATUS_FINISH.equals(task.getTaskStatus())
                || VMSystem.TASK_STATUS_CANCEL.equals(task.getTaskStatus())){
            throw new LogicException("该工单已完成或已取消，无法进行该操作");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_CANCEL  );
        task.setDesc(cancelVM.getDesc());
        updateTaskZSet(task,-1);
        return this.updateById(task);
    }

    /**
     * 完成工单
     * @param id
     * @return
     */
    @Override
    public boolean completeTask(long id) {
        TaskEntity taskEntity = this.getById(id);
        //（1）需要判断当前工单是否是未结束状态，如果是已完成或已取消则抛出异常。
        if (VMSystem.TASK_STATUS_FINISH.equals(taskEntity.getTaskStatus())
                || VMSystem.TASK_STATUS_CANCEL.equals(taskEntity.getTaskStatus())){
            throw new LogicException("该工单已完成或已取消，无法进行该操作");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
        this.updateById(taskEntity);
        //如果是投放工单或撤机工单
        if (VMSystem.TASK_TYPE_DEPLOY.equals(taskEntity.getProductTypeId())
        || VMSystem.TASK_TYPE_REVOKE.equals(taskEntity.getProductTypeId())){
            noticeVMServiceStatus(taskEntity);//运维工单封装与下发
        }
        //如果是补货工单
        if (VMSystem.TASK_TYPE_SUPPLY.equals(taskEntity.getProductTypeId())){
            noticeVMServiceSupply(taskEntity);
        }
        return true;
    }

    /**
     * 补货工单封装与下发
     * @param taskEntity
     */
    private void noticeVMServiceSupply(TaskEntity taskEntity) {
        //协议内容封装
        //1.根据工单id查询工单明细表
        QueryWrapper<TaskDetailsEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(TaskDetailsEntity::getTaskId,taskEntity.getTaskId());
        List<TaskDetailsEntity> taskDetailsList = taskDetailsService.list(qw);
        //2.构建协议内容
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(taskEntity.getInnerCode());//售货机编号
        List<SupplyChannel> supplyChannels = Lists.newArrayList();//补货类型
        //从工单明细表中提取数据到补货数据中
        taskDetailsList.forEach(td -> {
            SupplyChannel supplyChannel = new SupplyChannel();
            supplyChannel.setChannelId(td.getChannelCode());//货道编号
            supplyChannel.setCapacity(td.getExpectCapacity());//补货数量
            supplyChannels.add(supplyChannel);
        });
        supplyContract.setSupplyData(supplyChannels);
        //3.发送补货协议
        try {
            mqttProducer.send( TopicConfig.VMS_SUPPLY_TOPIC,2, supplyContract );
        } catch (Exception e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }


    /**
     * 运维工单封装与下发
     * @param taskEntity
     */
    private void noticeVMServiceStatus(TaskEntity taskEntity) {
        //向消息队列发送消息，通知售货机修改状态
        //封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());//工单类型
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());//售货机编号
        //发送消息
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2, taskCompleteContract);
        } catch (JsonProcessingException e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }

    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode="1002";
        if(isRepair){ //如果是运维工单
            roleCode="1003";
        }
        String key= VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+ regionId+"."+roleCode;
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 0);
        if(set==null || set.isEmpty()){
            return 0;  //如果没有数据则返回0
        }
        return (Integer)set.stream().collect( Collectors.toList()).get(0) ;
    }

    /**
     * 工单统计
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<TaskReportInfoVO> getTaskReportInfo(LocalDateTime start, LocalDateTime end) {
        List<TaskReportInfoVO> list = new ArrayList<>();

        //运营统计
        //1.运营工单总数统计
        int runTaskAllCount = getTaskCount(start, end, false, null);
        //2.运营工单完成统计
        int runOKCount = getTaskCount(start, end, false, VMSystem.TASK_STATUS_FINISH);
        //3.运营工单拒绝统计
        int runNOCount = getTaskCount(start, end, false, VMSystem.TASK_STATUS_CANCEL);
        //4.运营人员数统计
        Integer operatorCount = userService.getOperatorCount();
        //5.封装返回数据
        TaskReportInfoVO run = new TaskReportInfoVO();
        run.setTotal(runTaskAllCount);
        run.setCompletedTotal(runOKCount);
        run.setCancelTotal(runNOCount);
        run.setProgressTotal(0);
        run.setWorkerCount(operatorCount);
        run.setRepair(false);
        run.setDate(String.valueOf(LocalDate.now()));
        list.add(run);

        //运维统计
        //1.运维工单总数统计
        int opsTaskAllCount = getTaskCount(start, end, true, null);
        //2.运维工单完成统计
        int opsOKCount = getTaskCount(start, end, true, VMSystem.TASK_STATUS_FINISH);
        //3.运维工单拒绝统计
        int opsNOCount = getTaskCount(start, end, true, VMSystem.TASK_STATUS_CANCEL);
        //4.运维人员数统计
        Integer repairerCount = userService.getRepairerCount();
        //5.封装返回数据
        TaskReportInfoVO ops = new TaskReportInfoVO();
        ops.setTotal(opsTaskAllCount);
        ops.setCompletedTotal(opsOKCount);
        ops.setCancelTotal(opsNOCount);
        ops.setProgressTotal(0);
        ops.setWorkerCount(repairerCount);
        ops.setRepair(true);
        ops.setDate(String.valueOf(LocalDate.now()));
        list.add(ops);

        //返回结果
        return list;
    }

    /**
     * 根据条件查询统计工单
     * @param start
     * @param end
     * @param repair
     * @param taskStatus
     * @return
     */
    private int getTaskCount(LocalDateTime start, LocalDateTime end, boolean repair, Integer taskStatus) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        //范围时间条件
        qw.lambda().between(TaskEntity::getUpdateTime,start,end);
        //按人员角色查询
        if (repair) {
            //true运维人员，不查询补货工单
            qw.lambda().ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        } else {
            //false运营人员，只查询补货工单
            qw.lambda().eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        }
        //按工单状态
        if (taskStatus != null){
            qw.lambda().eq(TaskEntity::getTaskStatus,taskStatus);
        }
        return this.count(qw);
    }

    /**
     * 人效排名月度统计
     * @param start
     * @param end
     * @param isRepair
     * @param regionId
     * @return
     */
    @Override
    public List<UserWorkVO> personnelRank(LocalDate start, LocalDate end, boolean isRepair, Integer regionId) {

        String startTime = start + " 00:00:00";
        String endTime = end + " 23:59:59";

        QueryWrapper<TaskEntity> qw = new QueryWrapper();
        //判断是否是运维
        if (isRepair){
            //是，查询除完成补货工单类型外
            qw.lambda().ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else {
            //否，查询补货工单类型
            qw.lambda().eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }

        //判断区域
        if (regionId != 0){
            qw.lambda().eq(TaskEntity::getRegionId,regionId);
        }
        qw.select("count(user_id) as user_id , user_name")
                .lambda()
                //按照时间范围
                .between(TaskEntity::getUpdateTime,startTime,endTime)
                //只查询完成工单
                .eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_FINISH)
                //按照人员名称进行分组
                .groupBy(TaskEntity::getUserName)
                //按照人员id出现次数降序排序
                .orderByDesc(TaskEntity::getUserId)
                //只查询10条数据
                .last("limit 10");

        List<TaskEntity> list = this.list(qw);
        List<UserWorkVO> collect = list.stream().map(m -> {
            UserWorkVO userWorkVO = new UserWorkVO();
            userWorkVO.setUserName(m.getUserName());
            userWorkVO.setWorkCount(m.getUserId());
            return userWorkVO;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 工单状态统计(柱状图)
     * @return
     */
    @Override
    public List<TaskStatusCountVO> getEverydayTaskStatusCount(LocalDate start, LocalDate end) {
        List<TaskStatusCountVO> taskStatusCountVOList = Lists.newArrayList();
        //从开始日期到截至日期，逐条统计
        //datesUntil：按照给定的增量返回有序的日期流（参数1：结束时间，参数2：从起始时间到结束时间，每隔多长返回一条数据）
        start.datesUntil(end.plusDays(1), Period.ofDays(1))
                .forEach(date->{
                    var taskStatusCountVO = new TaskStatusCountVO();
                    taskStatusCountVO.setCollectDate(date.toString());
                    taskStatusCountVO.setProgressCount(count(date,VMSystem.TASK_STATUS_PROGRESS )); //进行中工单数
                    taskStatusCountVO.setFinishCount(count(date,VMSystem.TASK_STATUS_FINISH ));//完成工单数
                    taskStatusCountVO.setCancelCount(count(date,VMSystem.TASK_STATUS_CANCEL ));//取消工单数
                    taskStatusCountVOList.add(taskStatusCountVO);
                });
        return taskStatusCountVOList;
    }

    /**
     * 按时间和状态进行统计
     * @param start
     * @param taskStatus
     * @return
     */
    private int count(LocalDate start ,Integer taskStatus){
        var qw = new LambdaQueryWrapper<TaskEntity>();
        qw
                .ge(TaskEntity::getUpdateTime,start)
                .lt(TaskEntity::getUpdateTime,start.plusDays(1))
                .eq(TaskEntity::getTaskStatus, taskStatus);
        return this.count(qw);
    }
}
